﻿Imports System.IO
Imports System.ComponentModel
Imports SACommon

<ToolboxItem(False)>
Public Class ucDownload
    Private Async Sub ucDownload_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim success As Boolean

        gUpdateFiles.AppDirectory = UpdateCore.FixFolderText(Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.Personal)).FullName) & MyApp.ApplicationTitle

        SetUI()

        If UpdateCore.CurrentAppVersion Is Nothing Then UpdateCore.CurrentAppVersion = "0.0.0.0"
        If UpdateCore.CurrentAppVersion = "" Then UpdateCore.CurrentAppVersion = "0.0.0.0"

        Try
            Dim tResult = Await gUpdateVersion.CheckUpdate()
            If tResult.Result <> SAEventArgs.Results.Success Then Throw New Exception(tResult.Message)
            success = True
            If success = True Then
                'First check if updates are allowed
                If gUpdateVersion.AllowUpdate = False Then
                    Throw New Exception("Updates not allowed at the moment. Please try again later.")
                End If

                SetInstallTitle(MyApp.ApplicationTitle)

                gUpdateFiles.VersionURL = gUpdateVersion.RepositoryFileDefinitionFile
                '-----------------------------------------------------------------------
                'Read FileUpdate List
                success = Await gUpdateFiles.GetFileControlList
                If success = False Then
                    Throw New Exception("Invalid file control list")
                End If

                If gUpdateFiles.DownloadCount > 1 Then
                    lblFileCount.Text = gUpdateFiles.DownloadCount & " files"
                Else
                    lblFileCount.Text = "1 file"
                End If
                '-----------------------------------------------------------------------
            Else
                Throw New Exception
            End If

            If MyApp.IsUpdate = True Then
                gUpdateFiles.AppDirectory = Directory.GetParent(Application.StartupPath).FullName
                btnDir.Enabled = False
                txtDir.Enabled = False
            End If

            txtDir.Text = gUpdateFiles.AppDirectory
            If txtDir.Text <> "" Then
                btnAction.Enabled = True
                btnFWDownload.Enabled = True
            End If

        Catch ex As Exception
            ShowErrorMessage(ex.Message)
        End Try
    End Sub
    Sub SetUI()
        btnAction.Enabled = False
        btnFWDownload.Enabled = False
        lblMessage.Text = ""
        lblVersion.Text = ""
        lblFileCount.Text = ""
        txtDir.Text = ""
        lblError.Visible = False

        lblInstallFolderTitle.Text = MyApp.ApplicationTitle & " installation folder:"

        If gGenInfo.VistaOrBetterInstalled = True Then
            lblOS.Text = "Windows Vista or newer installed."
            pbOSStatus.Image = ImageList1.Images(1)
        Else
            lblFramework.Text = "pharmatrack require Windows Vista, 7, 8 or 8.1 to operate."
            pbOSStatus.Image = ImageList1.Images(0)
        End If

        If gGenInfo.FrameworkInstalled = True Then
            lblFramework.Text = gGenInfo.Framework
            pbFWStatus.Image = ImageList1.Images(1)
        Else
            lblFramework.Text = ".NET Framework 4.5 or above not installed. Please download and install."
            btnFWDownload.Visible = True
            pbFWStatus.Image = ImageList1.Images(0)
        End If

        'Check for connection and stop
        If UpdateCore.Connected(False) = False Then
            lblMessage.Text = "Please connect to the internet to install pharmatrack."
            lblVersion.Text = "pharmatrack can not be installed."
            txtDir.Enabled = False
            lblConnected.Text = "Not connected to the Net"
            pbConnected.Image = ImageList1.Images(0)
            btnAction.Enabled = False
        Else
            pbConnected.Image = ImageList1.Images(1)
            lblConnected.Text = "Connected to the Net"
        End If

        pbSettingsfile.Image = Nothing
        lblSettingsFile.Text = ""
    End Sub
    Private Async Sub btnAction_Click(sender As Object, e As EventArgs) Handles btnAction.Click
        Dim success As Boolean
        Try
            If Directory.Exists(gUpdateFiles.AppDirectory) = False Then Directory.CreateDirectory(gUpdateFiles.AppDirectory)
            gUpdateSettings.VersionURL = gUpdateVersion.RepositorySettingsDefinitionFile
            'Read SettingsUpdate List
            success = Await gUpdateSettings.GetSettingsControlList
            If success = False Then
                pbSettingsfile.Image = ImageList1.Images(0)
                lblSettingsFile.Text = "Invalid Settings Control file"
                Throw New Exception("Invalid control file list")
            Else
                pbSettingsfile.Image = ImageList1.Images(1)
                lblSettingsFile.Text = "Valid Settings Control file"
            End If
        Catch ex As Exception
            ShowErrorMessage(ex.Message)
        End Try
        '-----------------------------------------------------------------------
        If success = True Then
            Messenger.SendMessage(Messenger.MessageType.AppEvent, "InstallStarted", True)
            gApp.ChangePage(MyApp.ApplicationType.DownloadFiles, True)
        Else
            gApp.ChangePage(MyApp.ApplicationType.EndApplication, False)
        End If
    End Sub
    Private Sub btnDir_Click(sender As Object, e As EventArgs) Handles btnDir.Click
        Dim openDirDialog As FolderBrowserDialog = New FolderBrowserDialog() With {.ShowNewFolderButton = True}

        btnAction.Enabled = False
        btnFWDownload.Enabled = False
        If openDirDialog.ShowDialog = DialogResult.OK Then
            SetInstallFolder(openDirDialog.SelectedPath)
        End If
    End Sub
    Sub SetInstallFolder(Folder As String)
        txtDir.Text = Folder
        If txtDir.Text.Trim <> "" Then
            gUpdateFiles.AppDirectory = txtDir.Text.Trim
            btnAction.Enabled = True
            btnFWDownload.Enabled = True
        End If
    End Sub
    Sub SetInstallTitle(Title As String)
        'Check if the file version is valid
        If MyApp.IsUpdate = True Then
            lblVersion.Text = "Update "
        Else
            lblVersion.Text = "Install "
        End If
        lblVersion.Text &= String.Format("{0} {1}", Title, gUpdateVersion.NewApplicationVersion)
        If gUpdateVersion.IsBeta = True Then lblVersion.Text &= " " & gUpdateVersion.NewType
        pbConnected.Image = ImageList1.Images(1)
    End Sub
    Sub ShowErrorMessage(Message As String)
        lblMessage.Text = "Please contact support."
        lblVersion.Text = MyApp.ApplicationTitle & " can not be installed."
        txtDir.Enabled = False
        lblError.Text = Message
        lblError.Visible = True
        btnAction.Enabled = False
    End Sub
End Class
